import React, { Component } from 'react';
import {
  View,
  Text,
  TextInput,
  Button,
  StyleSheet,
  ScrollView,
  Image,
  TouchableOpacity,
  ImageBackground,
  ToastAndroid,
} from 'react-native';
import * as ImagePicker from 'react-native-image-picker';
import Icon from 'react-native-vector-icons/AntDesign';
import { style } from '../../../theme';
import { DOMAIN_URL, eventApplyAdd, eventApplyReview, uploadFile } from '../../../util/api';
import Loading from '../../compenent/Loading';
import { FILE_TYPE } from '../../../util/global';
import DeleteIcon from '../../compenent/DeleteIcon';

class ActiveApplyScreen extends Component {
  constructor(props) {
    super(props);
    let { apply } = props.route.params
    console.log('apply review', apply);

    this.state = {
      active: props.route.params?.active,
      data: apply,
      title: apply?.title || '',
      loading: false,
      description: apply?.description || '',
      images: [],
      preImages: props.route.params?.apply?.attachments || [],
    };
    console.log(this.state);
  }

  pickImage = () => {
    ImagePicker.launchImageLibrary(
      { mediaType: 'photo', selectionLimit: 5 },
      response => {
        if (!response.didCancel) {
          this.setState(prevState => ({
            images: [
              ...new Set([
                ...prevState.images,
                ...(response.assets.map(asset => asset) || []),
              ]),
            ],
          }));
        }
      },
    );
  };

  // submitData(): void {
  //   if (this.props.route.params?.action == global.Action.ADD) {
  //     eventApplyAdd({
  //       activityId: this.props.route.params.active.id,
  //       attachmentIds: [],
  //       description: '',
  //       title: '',
  //     }).then(v => {
  //       console.log(v);
  //     })
  //   }

  //   // throw new Error('Method not implemented.');
  // }
  submitData = async () => {
    let { action, active, apply } = this.props.route.params
    this.setState({ loading: true });
    let imgs: any[] = this.state.preImages.map(v => v.id);
    console.log(this.state.images);
    for (let index = 0; index < this.state.images.length; index++) {
      const element = this.state.images[index];
      await uploadFile(
        {
          uri: element.uri, // 替换为实际文件路径
          type: element.type,
          name: element.fileName,
        },
        FILE_TYPE.IMAGE,
      )
        .then(res => {
          console.log(res);
          if (res.code == 0) {
            console.log(`${element} upload success.`);
            imgs.push(res.data.id);
          } else {
            ToastAndroid.show(`上传失败:${res.msg}`, 2000);
          }
        })
        .catch(e => {
          console.log(e);
          ToastAndroid.show(`上传失败:${e}`, 2000);
        });
    }
    if (imgs.length > 0) {
      if (action == global.ACTION.ADD) {
        eventApplyAdd({
          activityId: active.id,
          attachmentIds: imgs,
          description: this.state.description,
          title: this.state.title,
        })
          .then(res => {
            console.log('add event', res);
            if (res.code == 0) {
              ToastAndroid.show('添加成功！', 3000);
              this.props.navigation.goBack({ refresh: true });
            } else {
              ToastAndroid.show(`添加失败:${res.msg}`, 3000);
            }
            return;
          })
          .finally(() => {
            this.setState({ loading: false });
          });
        // 编辑
        // const { data } = this.state
        // data.name = this.state.name
        // data.description = this.state.description
        // data.endTime = moment(this.state.endTime).format('YYYY-MM-DD HH:MM:SS')
        // data.image = imgs
        // data.score = Number.parseInt(this.state.score, 10)

        // eventUpdate(data).then(res => {
        //   console.log('update event', res);
        //   if (res.code == 0) {
        //     ToastAndroid.show('更新成功！', 3000);
        //     this.props.navigation.goBack({ refresh: true });
        //   } else {
        //     ToastAndroid.show(`更新失败:${res.msg}`, 3000);
        //     this.props.navigation.goBack({ refresh: true });
        //   }
        //   return;
        // }).catch(e => {
        //   this.props.navigation.goBack({ refresh: true });
        //   // DeviceEventEmitter.emit(PAGENAME.ACTIVE_DETAIL, { name: 'back' });

        // })
        //   .finally(() => {
        //     this.setState({ loading: false });
        //   });
      } else {
        // 更新

      }


    } else {
      this.setState({ loading: false });
    }
  };
  reviewApply(status: boolean): void {
    let statusString = status ? global.STATUS.APPROVED : global.STATUS.REJECTED
    eventApplyReview(this.state.data.approvalInfo.approvalId, statusString).then(res => {
      console.log(res);
      if (res.code == 0) {
        ToastAndroid.show('审批成功！', 2000)
        this.props.navigation.goBack()
      } else {
        ToastAndroid.show(`审批失败:${res.msg}`, 2000)
      }
    })
  }
  render() {
    const { title, description, images, preImages } = this.state;
    let { action, active, apply } = this.props.route.params
    console.log('action ', action);

    return (
      // <ImageBackground
      //   source={require('../../../assets/images/bg.jpg')} // 替换为您自己的背景图路径
      //   style={{ flex: 1 }}
      //   imageStyle={{ opacity: 0.4 }} // 修改透明度，范围为0（完全透明）到1（完全不透明）
      // >
      <View>
        <Loading loading={this.state.loading} />
        <ScrollView contentContainerStyle={styles.container}>
          <Text style={style.subTitle}>标题</Text>
          <TextInput
            editable={action == global.ACTION.ADD}
            style={styles.input}
            value={title}
            onChangeText={text => this.setState({ title: text })}
          />
          {action == global.ACTION.VIEW && (
            <>
              <Text style={style.subTitle}>申请人</Text>
              <TextInput
                editable={false}
                style={styles.input}
                value={title}
                onChangeText={text => this.setState({ title: text })}
              />
            </>
          )}
          <Text style={style.subTitle}>描述内容</Text>
          <TextInput
            editable={action == global.ACTION.ADD}
            style={[styles.input, { height: 100 }]}
            value={description}
            onChangeText={text => this.setState({ description: text })}
            multiline
          />
          <View style={{ flexDirection: 'row' }}>
            <Text style={style.subTitle}>图片</Text>
          </View>
          <View style={{ flexDirection: 'row', flexWrap: 'wrap' }}>
            {preImages.map((image, index) => (
              <View key={index} style={{ position: 'relative', margin: 4 }}>
                <Image
                  source={{ uri: `${DOMAIN_URL}${image.path}` }}
                  style={styles.image}
                />
                {action == global.ACTION.ADD && (
                  <TouchableOpacity
                    style={{
                      position: 'absolute',
                      top: 2,
                      right: 2,
                      backgroundColor: 'rgba(0, 0, 0, 0.5)',
                      width: 30,
                      height: 30,
                      justifyContent: 'center',
                      alignItems: 'center',
                    }}
                    onPress={() => {
                      const updatedImages = images.filter(
                        (value, idx) => idx !== index,
                      );
                      this.setState({ images: updatedImages });
                    }}>
                    <DeleteIcon />
                  </TouchableOpacity>
                )}
              </View>
            ))}
            {images.map((image, index) => (
              <View key={index} style={{ position: 'relative', margin: 4 }}>
                <Image source={{ uri: image.uri }} style={styles.image} />
                <TouchableOpacity
                  style={{
                    position: 'absolute',
                    top: 2,
                    right: 2,
                    backgroundColor: 'rgba(0, 0, 0, 0.5)',
                    width: 30,
                    height: 30,
                    justifyContent: 'center',
                    alignItems: 'center',
                  }}
                  onPress={() => {
                    const updatedImages = images.filter(
                      (value, idx) => idx !== index,
                    );
                    this.setState({ images: updatedImages });
                  }}>
                  <DeleteIcon />
                </TouchableOpacity>
              </View>
            ))}
            {action == global.ACTION.ADD &&
              <TouchableOpacity
                style={{
                  width: 75,
                  height: 75,
                  alignItems: 'center',
                  justifyContent: 'center',
                  borderWidth: 1,
                  borderColor: 'gray',
                  position: 'relative',
                  margin: 4,
                }}
                onPress={this.pickImage}>
                <Icon
                  name={'plus'}
                  size={50}
                  color={'rgba(0, 0, 0, 0.3)'}
                  style={{ width: 50, height: 50 }}
                />
              </TouchableOpacity>
            }
          </View>
          <View
            style={{
              flexDirection: 'row',
              alignSelf: 'center',
              marginVertical: 15,
            }}>
            <View style={style.pageButton}>
              {action == global.ACTION.ADD && (
                <Button title="提交" onPress={() => this.submitData()} />
              )}
              {global.USER.isadmin && action == global.ACTION.VIEW &&
                apply.approvalInfo.status == global.APPROVAL.PENDING && (
                  <View style={{ flexDirection: 'row' }}>
                    <Button
                      title="审批通过"
                      onPress={() => this.reviewApply(true)}
                    />
                    <View style={{ width: 10 }}>
                    </View>
                    <Button
                      title="不通过"
                      onPress={() => this.reviewApply(false)}
                    />
                  </View>
                )}
              {action == global.ACTION.VIEW &&
                apply.approvalInfo.status != global.APPROVAL.PENDING && (
                  <View>
                    <Button
                      disabled={true}
                      title={
                        apply.approvalInfo.status == global.APPROVAL.APPROVED
                          ? '已通过'
                          : apply.approvalInfo.status ==
                            global.APPROVAL.REJECTED
                            ? '未通过'
                            : '其他'
                      }
                    />
                  </View>
                )}
            </View>
          </View>
        </ScrollView>
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    padding: 20,
  },
  label: {
    fontSize: 16,
    marginBottom: 5,
  },
  input: {
    borderWidth: 1,
    borderColor: 'gray',
    borderRadius: 5,
    marginBottom: 10,
    padding: 10,
  },
  button: {
    fontSize: 16,
    color: 'blue',
    marginBottom: 10,
  },
  image: {
    width: 75,
    height: 75,
    marginBottom: 10,
  },
});

export default ActiveApplyScreen;
